package public

import (
	"fmt"
	"goDFS/etc"
	"log"
	"net"
	"regexp"
	"strconv"
	"strings"
)

//获取一个可以使用的端口
func GetAvailablePort() (int, error) {

	address, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:0", "0.0.0.0"))
	if err != nil {
		etc.SaveLog("[ GetAvailablePort ]"+err.Error(), 3)
		return 0, err
	}

	listener, err := net.ListenTCP("tcp", address)
	if err != nil {
		etc.SaveLog("[ GetAvailablePort ]"+err.Error(), 3)
		return 0, err
	}

	defer listener.Close()
	return listener.Addr().(*net.TCPAddr).Port, nil

}

//获取一个本机的局域网的ip
func GetIPv4s() (net.IP, error) {
	conn, err := net.Dial("udp", "8.8.8.8:80")
	if err != nil {
		etc.SaveLog("[ GetIPv4s ]"+err.Error(), 2)
		log.Fatal(err)
	}
	defer conn.Close()

	localAddr := conn.LocalAddr().(*net.UDPAddr)

	return localAddr.IP, nil
}

//服务地址
type StorageAddr struct {
	Ip   string
	Port int
}

func (b *StorageAddr) GetAddr() string {
	return fmt.Sprintf("%s:%d", b.Ip, b.Port)
}

//新建负载均衡地址
func NewStorageAddr(ip string, port string) *StorageAddr {
	ipR := regexp.MustCompile(`^\d{2,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$`)
	flag := ipR.MatchString(ip)
	if flag == false {
		return nil
	}
	p, err := strconv.Atoi(port)
	if err != nil {
		return nil
	}

	return &StorageAddr{
		Ip:   ip,
		Port: p,
	}

}

//新建一个同步负载地址

func DecodeToAddress(str string) []*StorageAddr {
	p := strings.Split(str, ";")
	var b []*StorageAddr

	p = p[:len(p)-1]
	for _, v := range p {
		f := strings.Split(v, ":")
		if len(f) == 2 {
			l := NewStorageAddr(f[0], f[1])
			b = append(b, l)
		}
	}

	return b

}
